import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class RechargePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('充值'),
        backgroundColor: Colors.white,
        elevation: 0,
      ),
      body: RechargeForm(),
    );
  }
}

class RechargeForm extends StatefulWidget {
  @override
  _RechargeFormState createState() => _RechargeFormState();
}

class _RechargeFormState extends State<RechargeForm> {
  int _selectedAmount = 0;
  final List<int> _amounts = [20, 50, 100, 500];
  final TextEditingController _customAmountController = TextEditingController();
  bool _showQRCode = false;
  Map<String, dynamic> userInfo = {};

  @override
  void initState() {
    super.initState();
    _getUserBalance();
  }

  void _recharge() async {
    setState(() {
      _showQRCode = true;
    });

    await Future.delayed(Duration(seconds: 2));
    int newBalance = _selectedAmount + await _getUserBalance();
    await _saveUserBalance(newBalance);

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('充值成功'),
          content: Text('您已成功充值 $_selectedAmount 元'),
          actions: <Widget>[
            TextButton(
              child: Text('确认'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  Future<int> _getUserBalance() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? userInfoString = prefs.getString('userInfo');
    if (userInfoString != null && userInfoString.isNotEmpty) {
      setState(() {
        userInfo = jsonDecode(userInfoString);
      });
    } else {
      // Handle case where userInfo is not stored yet
      userInfo = {'money': 0}; // or any default value you want
    }
    return userInfo['money'];
  }

  Future<void> _saveUserBalance(int balance) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    userInfo['money'] = balance;
    String userInfoString = jsonEncode(userInfo); // Convert to JSON string
    await prefs.setString("userInfo", userInfoString);
  }

  @override
  void dispose() {
    _customAmountController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.white, Colors.white],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '请选择充值金额',
              style: TextStyle(fontSize: 18, color: Colors.black),
            ),
            SizedBox(height: 16),
            Wrap(
              spacing: 10,
              children: _amounts.map((amount) {
                return ChoiceChip(
                  label: Text('$amount 元'),
                  selected: _selectedAmount == amount,
                  onSelected: (selected) {
                    setState(() {
                      _selectedAmount = (selected ? amount : 0);
                      _customAmountController.clear();
                    });
                  },
                );
              }).toList(),
            ),
            SizedBox(height: 30),
            Center(
              child: ElevatedButton(
                onPressed: _selectedAmount > 0 ? _recharge : null,
                child: Text('充值'),
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.symmetric(horizontal: 50, vertical: 15),
                ),
              ),
            ),
            SizedBox(height: 20),
            if (_showQRCode)
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '扫描二维码进行充值',
                    style: TextStyle(fontSize: 18, color: Colors.black),
                  ),
                  SizedBox(height: 10),
                  Center(
                    child: Container(
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.white, width: 3),
                        borderRadius: BorderRadius.circular(10),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black45,
                            blurRadius: 10,
                            offset: Offset(0, 5),
                          ),
                        ],
                      ),
                      child: Image.network(
                        'http://qny.cai142857.cn/pay.png',
                        height: 200,
                      ),
                    ),
                  ),
                ],
              ),
          ],
        ),
      ),
    );
  }
}
